/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.bpm.common.operation.OperatorEnum;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.config.CustomEvent;
import com.je.bpm.core.model.config.task.TaskDismissConfigImpl;
import com.je.bpm.core.model.task.KaiteBaseUserTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.delegate.DelegateHelper;
import com.je.bpm.engine.impl.bpmn.behavior.KaiteBaseUserTaskActivityBehavior;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.task.Comment;
import com.je.bpm.engine.task.GetTakeNodeNameUtil;

import java.util.Map;

import static com.je.bpm.engine.impl.bpmn.behavior.MultiInstanceActivityBehavior.NUMBER_OF_COMPLETED_INSTANCES;

/**
 * 驳回任务命令
 */
public class DismissTaskCmd extends AbstractJumpTask {

    /**
     * 驳回信息key
     */
    public static final String DISMISS_INFO_KEY = "dismissInfo";

    /**
     * 驳回节点
     */
    public static final String DISMISS_INFO_NODE_ID_KEY = "nodeId";

    /**
     * 驳回节点名称
     */
    public static final String DISMISS_INFO_NODE_NAME_KEY = "nodeName";

    private String comment;

    private String definitionKey;

    protected Map<String, Object> transientVariables;

    public DismissTaskCmd(String taskId, String definitionKey, String comment, Map<String, Object> bean, String prod) {
        super(taskId, prod, bean);
        this.taskId = taskId;
        this.comment = comment;
        this.definitionKey = definitionKey;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    @Override
    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    @Override
    protected Void execute(CommandContext commandContext, TaskEntity taskEntity) {
        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(taskEntity.getProcessDefinitionId());

        executeBeforeHandler(bpmnModel, taskEntity, CustomEvent.CustomEventEnum.TASK_TURN_DOWN_BEFORE, comment, OperatorEnum.TASK_DISMISS_OPERATOR);

        commandContext.getProcessEngineConfiguration().getTaskService().addComment(taskId, taskEntity.getProcessInstanceId(),
                Comment.NODE_TYPE, "审批驳回");

        commandContext.getProcessEngineConfiguration().getTaskService().addComment(taskId, taskEntity.getProcessInstanceId(),
                Comment.USER_COMMENT, comment);

        ExecutionEntity execution = taskEntity.getExecution();

        FlowElement flowElement = bpmnModel.getFlowElement(taskEntity.getTaskDefinitionKey());
        if (flowElement == null) {
            throw new ActivitiException("Can't find the flow element in the process definition.");
        }

        if (!(flowElement instanceof KaiteBaseUserTask)) {
            throw new ActivitiException("Only kaite user task can be jumped.");
        }
        KaiteBaseUserTask kaiteBaseUserTask = (KaiteBaseUserTask) flowElement;

        //驳回节点
        FlowElement targetFlowElement = bpmnModel.getFlowElement(definitionKey);
        String assignee = getHistoryAssigneeByTask(commandContext, taskEntity.getProcessInstanceId(), targetFlowElement);
        KaiteBaseUserTask targetBaseUserTask = (KaiteBaseUserTask) targetFlowElement;
        ExecutionEntity finalExecutionEntity;
        //删除任务之前调用审批告知
        String assigneeUsers = getHistoryAssigneeByTask(commandContext, taskEntity.getProcessInstanceId(), flowElement);
        Context.getCommandContext().getProcessEngineConfiguration().getProcessInstanceHelper()
                .addApprovalNotificationVariable(bpmnModel, kaiteBaseUserTask.getId(), comment, SubmitTypeEnum.DISMISS.getName());
        //如果属于多实例节点，在没有开始审批前可以跳转，但是一旦有人审批，则不可以跳转
        if (kaiteBaseUserTask.hasMultiInstanceLoopCharacteristics()) {
            Integer completed = getLoopVariable(execution, NUMBER_OF_COMPLETED_INSTANCES);
            if (completed != null && completed > 0) {
                throw new ActivitiException("The multi instance task already have approve record.");
            }
            //删除所有任务
            finalExecutionEntity = deleteAllMultiTask(commandContext, execution);
        } else {
            //删除当前任务
            commandContext.getTaskEntityManager().deleteTask(taskEntity, comment, false, false);
            finalExecutionEntity = execution;
        }

        finalExecutionEntity.setCurrentFlowElement(targetFlowElement);
        taskEntity.setTransientVariable(definitionKey, assignee);
        Object dismissInfoObjs = finalExecutionEntity.getVariable(DISMISS_INFO_KEY);
        JSONObject dismissInfos = new JSONObject();
        if (dismissInfoObjs != null) {
            dismissInfos = (JSONObject) dismissInfoObjs;
        }
        FlowElement lsatFlowElement = bpmnModel.getFlowElement(taskEntity.getTaskDefinitionKey());
        String nodeName = lsatFlowElement.getName();
        if (Strings.isNullOrEmpty(nodeName)) {
            nodeName = GetTakeNodeNameUtil.builder().getTakeNodeName(lsatFlowElement);
        }
        dismissInfos.put(targetFlowElement.getId(), buildDismissInfo(((KaiteBaseUserTask) bpmnModel.getFlowElement(taskEntity.getTaskDefinitionKey())).getTaskDismissConfig(),
                taskEntity.getTaskDefinitionKey(), nodeName));
        finalExecutionEntity.setVariable(DISMISS_INFO_KEY, dismissInfos);
        Context.getCommandContext().addAttribute(KaiteBaseUserTaskActivityBehavior.UPCOMINGINFO,
                DelegateHelper.buildUpcomingInfo(null, comment, SubmitTypeEnum.DISMISS, taskEntity.getBusinessKey(), "", null));
        //如果目标任务属于多实例节点，则要根据多实例要求创建多个任务（串行创建一个，并行创建多个）
        if (targetBaseUserTask.hasMultiInstanceLoopCharacteristics()) {
            Context.getAgenda().planContinueMultiInstanceOperation(finalExecutionEntity);
        } else {
            Context.getAgenda().planContinueProcessOperation(finalExecutionEntity);
        }
        executeAfterHandler(bpmnModel, taskEntity, CustomEvent.CustomEventEnum.TASK_TURN_DOWN_AFTER, comment, OperatorEnum.TASK_DISMISS_OPERATOR);
        return null;
    }


    private Map<String, Object> buildDismissInfo(TaskDismissConfigImpl taskDismissConfig, String nodeId, String nodeName) {
        Map<String, Object> dismissInfo = new JSONObject();
        dismissInfo.put("directSubmitAfterDismiss", taskDismissConfig.isDirectSendAfterDismiss());
        dismissInfo.put("disableSendAfterDismiss", taskDismissConfig.getDisableSendAfterDismiss());
        dismissInfo.put("forceCommitAfterDismiss", taskDismissConfig.isForceCommitAfterDismiss());
        dismissInfo.put(DISMISS_INFO_NODE_ID_KEY, nodeId);
        dismissInfo.put(DISMISS_INFO_NODE_NAME_KEY, nodeName);
        return dismissInfo;
    }

}
